package cn.wolfcode.luowowo.comment.service.impl;

import cn.wolfcode.luowowo.comment.domain.StrategyComment;
import cn.wolfcode.luowowo.comment.query.StrategyCommentQuery;
import cn.wolfcode.luowowo.comment.repository.IStrategyCommentRepository;
import cn.wolfcode.luowowo.comment.service.IStrategyCommentService;
import com.alibaba.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;
import java.util.Queue;

@Service
public class StrategyCommentServiceImpl implements IStrategyCommentService {

    @Autowired
    private IStrategyCommentRepository repository;

    @Autowired
    private MongoTemplate template;

    @Override
    public void commentThumbUp(String detailId, Long userId) {

        StrategyComment comment = repository.findById(detailId).get();
        List<Long> list = comment.getThumbuplist();

        //1. 当请求过来时，判断点赞用户id集合中是否有当前登录用户id
        if(!list.contains(userId)){
            //2. 如果当前用户id不存在集合中  表示点赞操作 点赞数 +1 将用户id添加到集合中
            comment.setThumbupnum(comment.getThumbupnum()+1);
            list.add(userId);
        }else{
            //3. 如果当前用户id存在集合中  表示取消点赞操作 点赞数 -1 将用户id在集合中删除
            comment.setThumbupnum(comment.getThumbupnum()-1);
            list.remove(userId);
        }
        repository.save(comment);
    }

    @Override
    public Page query(StrategyCommentQuery qo) {

        //repository  mongoTemplate  无法直接查询出page分页数据对象，所以需要自己手动封装

        //拼接条件
        Query query = new Query();
        if(qo.getDetailId() != -1){
            query.addCriteria(Criteria.where("detailId").is(qo.getDetailId()));
        }
        //查总数：select count(id) from xxx where ...
        long total = template.count(query, StrategyComment.class);
        if(total == 0){
            return Page.empty();  // 空的分页对象
        }

        //查当前页显示 list：select * from xxx where ... limit ...
        //需要设置分页信息和排序信息
        Pageable pageable = PageRequest.of(qo.getCurrentPage()-1,qo.getPageSize(), Sort.Direction.DESC,"createTime");
        query.with(pageable);
        List<StrategyComment> list = template.find(query, StrategyComment.class);
        return new PageImpl(list,pageable,total);
    }

    @Override
    public void save(StrategyComment comment) {
        //判断评论id是否为空，不为空则是更新
        if(!StringUtils.hasLength(comment.getId())){
            comment.setCreateTime(new Date());
        }
        repository.save(comment);
    }
}
